package top.zywork.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.zywork.common.ReflectUtils;
import top.zywork.wrapper.XssHttpServletRequestWrapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * XSSFilter过滤器类<br/>
 *
 * 创建于2019-01-25<br/>
 *
 * @author 王振宇
 * @version 1.0
 */
@Component(value = "myXssFilter")
@WebFilter(filterName="xssFilter", urlPatterns="/*")
@Slf4j
public class XssFilter implements Filter {

    private List<String> ignoreUrlList = new ArrayList<>();

    @Override
    public void init(FilterConfig config) {
        log.info("XSSFilter过滤器启动......");
        getXssFilterClass();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if (ignoreUrlList.contains(httpServletRequest.getRequestURI())) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(new XssHttpServletRequestWrapper(httpServletRequest), response);
        }
    }

    private void getXssFilterClass() {
        log.info("开始获取不需要XSS过滤的URL......");
        List<Class<?>> classList = ReflectUtils.getClasses("top.zywork.controller", false, top.zywork.annotation.XssFilter.class);
        if (classList != null && classList.size() > 0) {
            for (Class<?> clazz : classList) {
                top.zywork.annotation.XssFilter xssFilter = clazz.getDeclaredAnnotation(top.zywork.annotation.XssFilter.class);
                String[] ignoreUrls = xssFilter.ignoreUrls();
                ignoreUrlList.addAll(Arrays.asList(ignoreUrls));
            }
        }
        log.info("已获取不需要XSS过滤的URL......");
    }

   @Override
    public void destroy() {
        log.info("XSSFilter过滤器销毁......");
    }

}